package cn.sumpu.app.guoguojie.web.mvc.mobile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.taobao.api.internal.util.StringUtils;


import cn.sumpu.app.guoguojie.biz.AppconfBiz;
import cn.sumpu.app.guoguojie.biz.CmsContentBiz;
import cn.sumpu.app.guoguojie.biz.DoingBiz;
import cn.sumpu.app.guoguojie.biz.TopBiz;
import cn.sumpu.app.guoguojie.constant.DoingProductFrom;
import cn.sumpu.app.guoguojie.domain.CmsContent;
import cn.sumpu.app.guoguojie.domain.DoingProduct;
import cn.sumpu.app.guoguojie.domain.DoingProductTime;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.PageModel;

/**
 * @author sumpu
 * @version $Id: WapController.java, v 0.1 2012-9-21 上午11:15:46 sumpu Exp $
 */
@Controller
public class WapController {
    private static Logger   logger = LoggerFactory.getLogger(WapController.class);
    @Autowired
    private DoingBiz doingBiz;
    @Resource
    private TopBiz topBiz;
    @Resource
    private AppconfBiz confBiz;
    @Resource 
    private CmsContentBiz cmsContentBiz;
    
    @RequestMapping(value = "/wap/index.htm")
    public String index(String mid,HttpServletResponse response, HttpServletRequest request) throws IOException {
        PageModel pageModel = null;
        try {
            List<CmsContent> lunboList = cmsContentBiz.getContentList("99b3438a-354c-4ec3-b4f1-1a38f93a1ad9", 4);
            request.setAttribute("lunboList", lunboList);  
            pageModel = doingBiz.getFanliProduct(1);
        } catch (AppBusinessException e) {
            logger.error("[/wap/index.htm] fail", e);
        }
        request.setAttribute("pageModel", pageModel);
        request.setAttribute("mid", mid);
       return "v3/wap/index";
    }
    
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/wap/prolist.htm")
    public String prolist(Integer page,HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        Map<String,Object> mapRet = new HashMap<String,Object>();
        try {
            if(page == null){
                page = 1;
            }
            PageModel pageModel = doingBiz.getFanliProduct(page);
            mapRet.put("success", "true");
            mapRet.put("msg", "得到产品列表成功");
            mapRet.put("totalpage", pageModel.getTotalPage());
            if(pageModel.getList() != null && pageModel.getList().size() > 0){
                List<DoingProductTime> dptList = pageModel.getList();
                for (DoingProductTime doingProductTime : dptList) {
                    Map<String,Object> map = new HashMap<String,Object>();
                    map.put("picUrl", doingProductTime.getDoingProduct().getImageServer()+doingProductTime.getDoingProduct().getPicThumb()+"_200x200.jpg");
                    map.put("price", doingProductTime.getDoingProduct().getPrice());
                    map.put("proId", doingProductTime.getDoingProduct().getIdentifier());
                    map.put("name", doingProductTime.getDoingProduct().getName());
                    mapList.add(map);
                }
                
            }
            mapRet.put("list", mapList);
        } catch (AppBusinessException e) {
            logger.error("[/wap/prolist.htm] fail", e);
            mapRet.put("success", "false");
            mapRet.put("msg", "得到产品列表失败");
        }
        response.getWriter().print(JSONObject.fromObject(mapRet));
       return null;
    }
    
    
  //跳转到外站（如果是淘宝，加上淘宝客链接）
    @RequestMapping(value = "/wap/taobao.htm")
    public String taobao(HttpServletRequest request, HttpServletResponse response, String pid, String mid){
        try {
            DoingProduct dp = doingBiz.getDpById(pid); 
            if(dp != null && DoingProductFrom.TAOBAO.getValue().equals(dp.getFrom())){
                String taobaoLink = null;
                DoingProductTime dpt = doingBiz.getHasProductTime(pid);
                if(StringUtils.isEmpty(mid)){
                    mid = "guoguojie";
                }
                if (null == dpt) {
                    taobaoLink = topBiz.genTaobaoLink(mid, dp.getOriginalId(),true, confBiz.getGuoguojieCommissionRate());
                } else {
                    double gComRate = dpt.getGuoguojieCommissionRate();
                    double comRate = dpt.getCommissionRate();
                    double rate =  gComRate/comRate;
                    taobaoLink = topBiz.genTaobaoLink(mid, dp.getOriginalId(),true, rate);
                }
                
                if(taobaoLink != null){
                    response.sendRedirect(taobaoLink);
                }else{
                    response.sendRedirect(dp.getLinkUrl());
                }
            }else{
                if(dp != null){
                    response.sendRedirect(dp.getLinkUrl());
                }
            }
        } catch (Exception e) {
            logger.error("[/wap/prolist.htm] fail", e);
            return "v2/common/error";
        }
        return null;
    }
    
    
}
